package com.citi.gts.galto.modules.validation.rule.impl;

import com.citi.gts.galto.core.tools.exception.ReferenceException;
import com.citi.gts.galto.core.tools.factory.InvalidConfigurationException;
import com.citi.gts.galto.core.tools.reference.Field;
import com.citi.gts.galto.core.tools.reference.impl.CountryReference;
import com.citi.gts.galto.modules.validation.Precondition;
import com.citi.gts.galto.modules.validation.exception.SubServiceException;
import com.citi.gts.galto.modules.validation.exception.ValidationException;
import com.citi.gts.galto.modules.validation.vo.SampleInstruction;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class CountryExistenceRule extends LeafRule {

    @Resource
    protected CountryReference<String> countryReference;

    @Override
    @Precondition(rule = "countryInformedRule", currentRule = "countryExistenceRule")
    public void validate(SampleInstruction instruction) throws SubServiceException, ValidationException {

        System.out.println("Within " + getClass().getSimpleName());

        try {

            countryReference.find(instruction.getOrigCountryCode());

        } catch (InvalidConfigurationException e) {
            throw new SubServiceException(repair, "Invalid Country Code", e);

        } catch (IllegalArgumentException e) {
            throw new SubServiceException(repair, "Uninformed Country Code", e);

        }
    }

    @Override
    public void setFieldsValidated() throws ReferenceException {

        Set<Field> fieldValidatedSet = new HashSet<Field>(1);
        fieldValidatedSet.add(fieldReference.find("origCountryCode"));
        repair.setFieldSet(fieldValidatedSet);
    }

}

